import WebSocket, { WebSocketServer } from "ws";
import { getUserIdByToken } from "../service/tokenService.js";
import { saveMessage, getUnreadMessages } from "../service/messageService.js";
import Message from "../class/Message.js";

const port = process.env.SERVER_PORT;
const wss = new WebSocketServer({ port });

const clients = new Map(); // 此处可能需要修改成redis或其他存储方案

wss.on("connection", async function connection(ws, req) {
  let userId;
  console.log("Client connected", req.url);

  try {
    const token = req.url.split("?token=")[1];
    if (!token) throw new Error("未提供Token");

    userId = await getUserIdByToken(token);
    if (!userId) throw new Error("Token无效");

    clients.set(userId, {
      id: userId,
      ws,
      connectedAt: Date.now(),
    });

    ws.send(JSON.stringify(Message.createSystemMessage(userId, "连接成功！")));

    const unreadMessages = await getUnreadMessages(userId);
    unreadMessages.forEach((message) => {
      const messageObj = JSON.stringify(
        Message.createMessage(message.sender, message.receiver, message.message)
      );
      ws.send(messageObj);
    });
  } catch (error) {
    console.error("连接错误:", error.message);

    ws.send(
      JSON.stringify({
        type: "AUTH_FAILED",
        message: error.message,
      })
    );
    return ws.close(1008, "Authentication failed");
  }

  ws.on("message", function incoming(message) {
    try {
      let rawData = message.toString();
      let incomingMsg = JSON.parse(rawData);
      incomingMsg.sender = userId; // 设置发送者

      // 判断是单发还是群发
      const receivers = incomingMsg.receiver;
      if (!Array.isArray(receivers)) {
        console.error("receiver 应该是数组类型");
        return;
      }

      if (receivers.length === 1) {
        // 单发消息
        const receiverId = receivers[0];

        const outgoingMessage = Message.createMessage(
          userId,
          receiverId,
          incomingMsg.message
        );

        const outgoingStr = JSON.stringify(outgoingMessage);

        const targetClient = clients.get(receiverId);
        if (targetClient && targetClient.ws.readyState === WebSocket.OPEN) {
          targetClient.ws.send(outgoingStr);
        } else {
          console.log(`用户 ${receiverId} 不在线，保存离线消息`);
          saveMessage(outgoingMessage); // 保存对象，存数据库或文件时再转字符串
        }
      } else if (receivers.length > 1) {
        // 群发消息
        receivers.forEach((receiverId) => {
          const outgoingMessage = Message.createMessage(
            userId,
            receiverId,
            incomingMsg.message
          );

          const outgoingStr = JSON.stringify(outgoingMessage);

          const targetClient = clients.get(receiverId);
          if (targetClient && targetClient.ws.readyState === WebSocket.OPEN) {
            targetClient.ws.send(outgoingStr);
          } else {
            console.log(`用户 ${receiverId} 不在线，保存离线消息`);
            saveMessage(outgoingMessage);
          }
        });
      } else {
        console.error("无有效的接收者");
      }
    } catch (error) {
      console.error("消息处理错误:", error);
    }
  });

  ws.on("close", function close() {
    try {
      if (userId) {
        clients.delete(userId);
        console.log(`用户 ${userId} 断开，剩余用户数: ${clients.size}`);
      }
    } catch (error) {
      console.error("连接关闭处理错误:", error);
    }
  });
});

wss.on("close", function close() {
  console.log("Server closed");
});

wss.on("error", function error(err) {
  console.error("Server error", err);
});

// 心跳检测
setInterval(function () {
  try {
    clients.forEach((meta, userId) => {
      if (meta.ws.readyState !== WebSocket.OPEN) {
        clients.delete(userId);
      }
    });
  } catch (error) {
    console.error("心跳检测错误:", error);
  }
}, 30000);

console.log("Server started");

export default wss;
